<?php
namespace app\controllers;

use app\models\Images;
use app\modules\models\CooperateApp;
use OSS\OssClient;
use Yii;
use tools;
use yii\web\Response;

use yii\rest\ActiveController;
/**
 * 图片控制器
 * @author 黄宇翔
 * @access public
 * @since 1.0
 */
class ImagesController extends ActiveController
{
	public $app_id;
	public $bucket='imageliwei';
	public $endpoint;//阿里云
	public $ossClient;
	public $toolsClass;
	public $accessKeyId;//阿里id
	public $accessKeySecret;//阿里secret
	public $imageSize = 2000000;
	public $enableCsrfValidation = false;
	public $modelClass = 'app\models\Images';
	public $imageType = array('image/gif', 'image/jpeg', 'image/pjpeg', 'image/png');
	public function actions()
	{
		$actions = parent::actions();
		unset($actions['index'], $actions['update'], $actions['create'], $actions['delete'], $actions['view']);

		return $actions;
	}
	public function prompt($code, $promptInfo, $data = NULL, $type = 'array')
	{
		$this->toolsClass = new \tools();
		if ($type == 'json') {
			header('Content-type: application/json');
			$data = $this->toolsClass->prompt($code, $promptInfo, $data);
			echo(json_encode($data));
			die;
		}

		return $this->toolsClass->prompt($code, $promptInfo, $data);
	}
	/**
	 * 图片上传
	 * @author 黄宇翔
	 * @access public
	 * @param mixed $cont 上传图片值
	 * @param mixed $type_图片类型
	 * @param mixed $path 文件夹名称
	 * @since 1.0
	 * @return array
	 */
	public function actionCreate()
	{
		$imagesModel = new Images();
		$request = Yii::$app->request;
		$imagesModel->attributes = $request->post();
		if (!$imagesModel->validate())
		{
			return $this->prompt('400', $imagesModel->errors);
		}
		$path = $request->post('path','/book/');//路径
		$type = $request->post('cont_type','image/jpeg');//图片格式
		$cont = $request->post('cont');
		//$cont=file_get_contents('20101017211314-985626572.jpg');
		$groupId = $request->post('group_id');
		if (!in_array($type, $this->imageType)) {
			return $this->prompt('400', '图片格式不支持');
		}
		$this->cooperateAli();
		$object = $path.'/';
		$imageName = time().substr(md5(time()),0,8);//生成随机id
		$imageUrl = substr($type, 6);
		$object .= $imageName . '.' . $imageUrl;//拼接图片jpg
		//上传阿里云
		$upload = $this->ossClient->putObject($this->bucket, $object, $cont);
		if ($upload == null) {
			$data = array(
					'id' => $imageName,
					'app_id' => 'aa',
					'image' => "http://" . $this->bucket . ".oss-cn-shanghai.aliyuncs.com/" . $object,
					'content_length' => strlen($cont),
					'source_type' => 'BACK',//'用户 CUSTOMER  后台 BACK'
					'create_time' => time()
			);
			$res = $imagesModel->insertImages($data);
			if ($res) {
				return $data['image'];
			} else {
				return $this->prompt('500', '图片插入数据失败');
			}

		} else {
			return $this->prompt('500', '图片上传失败');
		}
	}

	/**
	 * 阿里云数据
	 * @author 黄宇翔
	 * @access public
	 * @since 1.0
	 * @return array
	 */
	public function cooperateAli()
	{
		$CooperateAppModel = new \app\models\CooperateApp();
		$cooperateAli = $CooperateAppModel->findPerate('8us0m1kt5742o9n7', 'ALIYUN');
		if ($cooperateAli) {
			$oss = json_decode($cooperateAli['output_config']);
			$this->accessKeyId = $oss->accessKeyId;
			$this->accessKeySecret = $oss->accessKeySecret;
			$this->endpoint = $oss->endpoint;
			$this->bucket = $oss->bucket;
			$this->ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);
			if ($this->ossClient) {
				return $cooperateAli['id'];
			}
		}
		return $this->prompt('500', 'ALIYUN配置');
	}

	/**
	 * 图片删除控制器
	 * @author 黄宇翔
	 * @access public
	 * @param mixed $path 文件夹名称
	 * @param mixed $name 图片名字
	 * @since 1.0
	 * @return array
	 */
	public function actionDelete()
	{
		$aliId = $this->cooperateAli();
		$imagesModel = new Images();
		$imagesGroupModel = new ImagesGroup();
		//$path = Yii::$app->request->post('path');//分组
		$id = Yii::$app->request->post('id');//名字
		if (!$id) {
			return $this->toolsClass->prompt('400', '缺少必须的参数 id');
		}
		$imagesDate = $imagesModel::find()->where(array('id' => $id, 'app_id' => $this->app_id))->one();
		if (!$imagesDate) {
			return $this->toolsClass->prompt('500', '没有这个图片');
		}
		$imageUrl = explode('/', $imagesDate['image']);
		unset($imageUrl[0], $imageUrl[1], $imageUrl[2]);
		if (count($imageUrl) > 1) {
			$object = $imageUrl[3] . '/' . $imageUrl[4];
		} else {
			$object = $imageUrl[3];
		}
		try {
			$this->ossClient->deleteObject($this->bucket, $object);
		} catch (OssException $e) {
			return $this->toolsClass->prompt('500', '阿里云图片删除失败');
		}
		$imagesGroup = $imagesModel->findGroupId($id, $this->app_id);//查询图片是否已有分组
//删除图片total-1
		if ($imagesGroup['group_id']) {
			if (!$imagesGroupModel->redTotal ( $imagesGroup['group_id'] )) {
				return $this->toolsClass->prompt ( '500' , 'total减少失败' );
			}
		}
		if (!$imagesModel->deleteImages($id, $this->app_id)) {
			return $this->toolsClass->prompt('500', '数据库记录删除失败');
		}

		return $this->toolsClass->prompt('200', 'SUCCESS');
	}

	/**
	 * 图片移动分组控制器
	 * @author 黄宇翔
	 * @access public
	 * @param mixed $imagesId 图片id
	 * @param mixed $groupId 分组id
	 * @since 1.0
	 * @return array
	 */
	public function actionUpdate()
	{
		$request = Yii::$app->request;
		if ($request->isPut || $request->isPatch) {
			$imagesId = $request->post('images_id');
			$groupId = $request->post('group_id');

			if (!$imagesId) {
				return $this->toolsClass->prompt('400', '缺少必须的参数: images_id');
			} else if (!$groupId) {
				return $this->toolsClass->prompt('400', '缺少必须的参数: group_id');
			}
			$imagesGroupModel = new ImagesGroup();

			if (!$imagesGroupModel::find()->where(array('id' => $groupId, 'app_id' => $this->app_id))->one()) {
				return $this->toolsClass->prompt('400', '没有这个分组');
			}
			if (strpos($imagesId, ',')) {
				$groupImage = explode(',', $imagesId);
				foreach ($groupImage as $k) {
					$imagesModel = new images();
					$beforeGroup = $imagesModel->findGroupId($k, $this->app_id);//查询图片是否已有分组
					//更新图片分组
					if (!$imagesModel->updateImages($groupId, $k)) {
						return $this->toolsClass->prompt('500', '图片移动失败');
					}

					if (!$imagesGroupModel->addTotal($groupId)) {
						return $this->toolsClass->prompt('500', 'total增加失败');
					}
					if (!$beforeGroup) {
						if (!$imagesGroupModel->redTotal($beforeGroup['group_id'])) {
							return $this->toolsClass->prompt('500', 'total减少失败');
						}
					}
				}
			} else {
				$imagesModel = new images();
				$beforeGroup = $imagesModel->findGroupId($imagesId, $this->app_id);//查询图片是否已有分组
				//更新图片分组
				if (!$imagesModel->updateImages($groupId, $imagesId)) {
					return $this->toolsClass->prompt('500', '图片移动失败');
				}

				if (!$imagesGroupModel->addTotal($groupId)) {
					return $this->toolsClass->prompt('500', 'total增加失败');
				}
				if (!$beforeGroup) {
					if (!$imagesGroupModel->redTotal($beforeGroup['group_id'])) {
						return $this->toolsClass->prompt('500', 'total减少失败');
					}
				}
			}

			return $this->toolsClass->prompt('200', 'SUCCESS');
		}
	}
    /**
     * 图片获取列表
     * @author 黄宇翔
     * @access public
     * @param mixed $imagesId 图片id
     * @param mixed $groupId 分组id
     * @since 1.0
     * @return array
     */
	public function actionIndex ()
    {
        $materialGet['pageno'] = Yii::$app->request->get('pageno');
        $materialGet['limit'] = Yii::$app->request->get('limit');
		$materialGet['group_id'] = Yii::$app->request->get('group_id');
        if (!$materialGet['pageno']) {
            return $this->toolsClass->prompt('400', '请输入页数:pageno');
        } else if (!$materialGet['limit']) {
            return $this->toolsClass->prompt('400', '每页数:limit');
        }
        $imagesModel = new Images();
		$model = $imagesModel->findByItems($this->app_id, $materialGet['limit'], $materialGet['pageno'], $materialGet['group_id']);
        if ($model) {
            return $this->toolsClass->prompt('200', 'SUCCESS', $model);
        }
        return $this->toolsClass->prompt('500', '查询内部错误');

    }
}
?>